package my.stock.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.SneakyThrows;
import my.stock.util.EntityUtil;
import my.stock.util.HttpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class StockAnalyzerBak {

    private static final String API_URL = "http://q.10jqka.com.cn/thshy/detail/field/199112/order/desc/page/%d/ajax/1/code/%s";
    private Logger logger = LoggerFactory.getLogger(StockAnalyzerBak.class);

    @Autowired
    HttpUtil httpUtil;
    @Autowired
    JSONArray stocks;

    @SneakyThrows
    // 取第一页的数据
    public List<Map<String, Object>> analyze(String code) {
        List<Map<String, Object>> list = new ArrayList<>();
        this.analyze(1, code, list);
        return list;
    }

    // 取某一页的数据
    private void analyze(int pageNo, String code, List<Map<String, Object>> list) {
        // 改变 url
        String url = String.format(API_URL, pageNo, code);
        // 发送请求
        String response = httpUtil.openUrl(url);
        // 解析结果
        list.addAll(this.extract(url, response));

        if (pageNo == 1) {
            // 处理多页
            Element pageInfo = Jsoup.parse(response).selectFirst(".page_info");
            if (null != pageInfo) {
                String pages = pageInfo.text();
                int page = Integer.parseInt(pages.substring(pages.indexOf("/") + 1));

                // 每一页都处理一下
                for (int i = 2; i < page; i++) {
                    this.analyze(i, code, list);
                }
            }
        }
    }

    @SneakyThrows
    // 解析所有行
    private List<Map<String, Object>> extract(String url, String response) {
        List<Map<String, Object>> list = new ArrayList<>();

        Document document = Jsoup.parse(response);
        Elements trs = document.select("table > tbody > tr");
        if (null == trs || trs.size() == 0) {
            logger.error("====stocks trs null====url====" + url);
        }

        for (Element tr : trs) {
            list.add(this.extract(tr.select("td")));
        }

        return list;
    }

    // 解析一行的所有列
    private Map<String, Object> extract(Elements tds) {
        Map<String, Object> values = new HashMap<>();
        for (int i = 0, length = tds.size(); i < length; i++) {

            JSONObject subject = stocks.getJSONObject(i);
            if (EntityUtil.isSkip(subject)) {
                continue;
            }

            Element td = tds.get(i);
            String value = td.text();

            // 保存值
            values.put(subject.getString("field"), value);
        }

        return values;
    }
}
